/**
 * Created with IntelliJ IDEA.
 * Description: leetcode: 206. 反转链表
 * <a href="https://leetcode.cn/problems/reverse-linked-list/">...</a>
 * User: DELL
 * Date: 2023-10-10
 * Time: 9:41
 */
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    /**
     * 解题思路:(双指针)
     * 在遍历链表时,将当前节点的 next 指针改为指向前一个节点.由于节点没有引用其前一个节点，
     * 因此必须事先存储其前一个节点.在更改引用之前，还需要存储后一个节点.最后返回新的头引用.
     * 因此定义两个指针,遍历反转即可.
     *
     * @param head
     * @return
     */
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}
